package com.smfx.yxt.excel.tags;

import java.util.StringTokenizer;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;

import com.smfx.yxt.excel.ExcelParser;
import com.smfx.yxt.excel.ExcelUtils;
import com.smfx.yxt.excel.WorkbookUtils;

/**
 * *
 * <p>
 * <b>DeclareTag </b> is a class which parse #declare tag
 * </p>
 * #declare ${..} ${..} ...
 */
public class DeclareTag implements ITag {
    public static final String KEY_DECLARE = "#declare";

    public int[] parseTag(HSSFSheet sheet, HSSFRow curRow, HSSFCell curCell) {
        String cellstr = curCell.getRichStringCellValue().getString();
        String expr = cellstr.substring(KEY_DECLARE.length() + 1).trim();
        if (expr.length() > 0) {
            StringTokenizer st = new StringTokenizer(expr, " ");
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                int sPos = token.indexOf(ExcelParser.EXPR_OPEN);
                if (sPos >= 0) {
                    int ePos = token.indexOf(ExcelParser.EXPR_CLOSE, sPos + ExcelParser.EXPR_OPEN.length());
                    if (ePos >= 0) {
                        ExcelUtils.addValue(token.substring(sPos + ExcelParser.EXPR_OPEN.length(), ePos).split("=")[0],
                                ExcelParser.parseExpr(token));
                    }

                }
                sheet.removeRow(WorkbookUtils.getRow(curRow.getRowNum(), sheet));
                sheet.shiftRows(curRow.getRowNum() + 1, sheet.getLastRowNum(), -1);
            }
        }
        return new int[] { 0, 0, 0 };
    }

    public String getTagName() {
        return KEY_DECLARE;
    }

    public boolean hasEndTag() {
        return false;
    }
}
